<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Banner;
use app\common\model\Promise as PromiseModel;
use app\common\model\Teacher;
use app\common\model\User as UserModel;
use app\common\model\TeacherAudit;
use app\common\validate\SchoolApply as SchoolApplyValidate;
use app\common\model\SchoolApply as SchoolApplyModel;
use think\Db;
use think\Exception;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $param = $this->request->post();

        $param['where'] = [
            'recommend' => 1
        ];
        $param['limit'] = 10;
        $data['teacher'] = (new Teacher)->getLists($param);

        $data['banner'] = (new Banner())->select();

        $data['promise'] = (new PromiseModel)->order('weigh desc,id desc')->select();

        $this->success('请求成功',$data);
    }

    //付费入口，需要审核过的机构才能进行查看
    public function settled_route()
    {
        $user_id = $this->auth->id;
        $is_school = UserModel::where([
            'id' => $user_id,
        ])->value('is_school');
        $this->success('付费入口',$is_school);
    }

    //教师权限入口
    public function teacher_route()
    {
        //todo 测试接单不需要是老师也能接单
        $this->success('可以进入');
        $teacher = Db::name('teacher')->where([
            'user_id' => $this->auth->id,
            'deletetime' => Db::raw('deletetime IS NULL')
        ])->find();
        if(!$teacher){
            $this->error('请先入驻成为家教再进行操作');
        }
        $this->success('可以进入');
    }

    //提交单位信息
    public function school_apply()
    {
        $param = $this->request->post();
        $user_id = $this->auth->id;

        try{
            $param['user_id'] = $user_id;
            $validate = new SchoolApplyValidate();
            if (!$validate->scene('add')->check($param)) {
                throw new Exception($validate->getError());
            }
            (new SchoolApplyModel)->save([
                'user_id' => $user_id,
                'apply_nickname' => $param['apply_nickname'],
                'apply_mobile' => $param['apply_mobile'],
                'apply_school' => $param['apply_school'],
            ]);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }

        $this->success('');
    }
}
